package com.hyperf.core.lock.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁原生RedisTemplate处理器
 *
 * @author lizhaoyang
 */
public class RedisTemplateLockExecutor extends AbstractLockExecutor<RedisInterProcessMutex> {

    private static final Logger logger = LoggerFactory.getLogger(RedisTemplateLockExecutor.class);

    private static final String LOCK_KEY_PREFIX = "lock::";

    private StringRedisTemplate stringRedisTemplate;

    public RedisTemplateLockExecutor() {
    }

    public RedisTemplateLockExecutor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public RedisInterProcessMutex acquire(String lockKey, String lockValue, long expire, long acquireTimeout) {
        RedisInterProcessMutex mutex = new RedisInterProcessMutex(stringRedisTemplate, LOCK_KEY_PREFIX + lockKey, lockValue);
        boolean locked = mutex.acquire(expire, TimeUnit.MILLISECONDS);
        return obtainLockInstance(locked, mutex);
    }

    @Override
    public boolean releaseLock(String lockKey, String lockValue, RedisInterProcessMutex lockInstance) {
        try {
            lockInstance.release();
        } catch (Exception exception) {
            logger.error("RedisTemplateLockExecutor release lock error, ", exception);
            return false;
        }
        return true;
    }

    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
}
